import menu from './menu.json?raw'
import route from './route.json?raw'

export const getMenu = () => {
  return JSON.parse(menu)
}

export const getRoute = () => {
  return JSON.parse(route)
}

export const getDataByPermissions = (data, permissions) => {
  const deletes = []
  const recursion = (d, i, data) => {
    if (d.children.length > 0) {
      d.children.forEach(recursion)
    }
    if (d.permissions && !d.permissions.find((p) => permissions.includes(p))) {
      //   data[i] = null
      //   data.splice(i, 1)
      deletes.push([data, i])
    }
  }
  data.forEach(recursion)
  deletes.sort(([, i1], [, i2]) => i2 - i1).forEach(([data, i]) => data.splice(i, 1))
  return data
}

export const getMenuByPermissions = ({ root = false, permissions = [] }) => {
  const menus = getMenu()
  if (root) {
    return menus
  }
  return getDataByPermissions(menus, permissions)
}

export const getRouteByPermissions = ({ root = false, permissions = [] }) => {
  const routes = getRoute()
  if (root) {
    return routes
  }
  return getDataByPermissions(routes, permissions)
}
